package com.kzw.oa.model.system;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.annotation.XmlTransient;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.google.gson.annotations.Expose;
import com.kzw.core.menu.TopModule;
import com.kzw.core.util.AppUtil;

@SuppressWarnings("serial")
public class AppUser implements UserDetails, Serializable {
	/**
	 * 超级管理员ID,由初始化数据加入
	 */
	public static final Long SUPER_USER = new Long(1);

	@Expose
	protected Long userId;
	@Expose
	protected String username;
	protected transient String password;
	@Expose
	protected String email;
	// 所属部门
	protected Department department;
	@Expose
	protected Long jobId;
	@Expose
	protected String phone;
	@Expose
	protected String mobile;
	@Expose
	protected String fax;
	@Expose
	protected String address;
	@Expose
	protected String zip;
	@Expose
	protected String photo;
	@Expose
	protected Date accessionTime = new Date();

	// 状态：1(正常)， 0(不可用)
	@Expose
	protected Short status;
	@Expose
	protected String education;
	@Expose
	protected Short title; // 性别
	@Expose
	protected String fullname;
	@Expose
	protected Short delFlag = 0;	
	@Expose
	protected String depNames;
	@Expose
	protected String posNames;
	@Expose
	protected String roleNames;

	/** 用户所属部门的优先级 */
	private Integer orgSn;
	/** 用户在此部门中的优先级 */
	private Integer userSn;
	/** 职务：数据字典 */
	private String dutyIds;
	private String dutyNames;
	// 编号
	private String userCode;
	// 职称
	private String zhicheng;
	// 所属教研室
	private String jiaoyanshi;

	// 用户类型
	@Expose
	private int roleType = 3;
	// 所在主部门Id
	@Expose
	protected Long orgId;
	
	// 选题次数[学生有效]
	private Integer xtcnt;
	

	@XmlTransient
	protected Set<AppRole> roles = new HashSet<AppRole>();

	/**
	 * 用户头部的模块菜单，由用户登录后设置
	 */
	private Map<String, TopModule> topModules = new LinkedHashMap<String, TopModule>();

	/**
	 * 用于存储该用户的权限,需要合并公共的
	 */
	protected Set<String> rights = new HashSet<String>();
	/**
	 * 用户所属的组织架构
	 */
	protected Set<UserOrg> orgs = new HashSet<UserOrg>();


	public Set<String> getRights() {
		return rights;
	}

	public Map<String, TopModule> getTopModules() {
		return topModules;
	}

	public void setTopModules(Map<String, TopModule> topModules) {
		this.topModules = topModules;
	}

	/**
	 * 取得所有的Function的权限，则以_为开头的权限
	 */
	public String getFunctionRights() {
		StringBuffer sb = new StringBuffer();

		Iterator<String> it = rights.iterator();

		while (it.hasNext()) {
			sb.append(it.next()).append(",");
		}

		if (rights.size() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}

		return sb.toString();
	}

	public void setRights(Set<String> rights) {
		this.rights = rights;
	}

	/**
	 * Default Empty Constructor for class AppUser
	 */
	public AppUser() {
		super();
	}

	/**
	 * Default Key Fields Constructor for class AppUser
	 */
	public AppUser(Long in_userId) {
		this.setUserId(in_userId);
	}

	public Long getUserId() {
		return this.userId;
	}

	/**
	 * Set the userId
	 */
	public void setUserId(Long aValue) {
		this.userId = aValue;
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String aValue) {
		this.username = aValue;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String aValue) {
		this.password = aValue;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String aValue) {
		this.email = aValue;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public Long getJobId() {
		return this.jobId;
	}

	public void setJobId(Long aValue) {
		this.jobId = aValue;
	}

	public String getPhone() {
		return this.phone;
	}

	public void setPhone(String aValue) {
		this.phone = aValue;
	}

	public String getMobile() {
		return this.mobile;
	}

	public void setMobile(String aValue) {
		this.mobile = aValue;
	}

	public String getFax() {
		return this.fax;
	}

	public void setFax(String aValue) {
		this.fax = aValue;
	}

	public String getAddress() {
		return this.address;
	}

	public void setAddress(String aValue) {
		this.address = aValue;
	}

	public String getZip() {
		return this.zip;
	}

	public void setZip(String aValue) {
		this.zip = aValue;
	}

	public String getPhoto() {
		return this.photo;
	}

	public void setPhoto(String aValue) {
		this.photo = aValue;
	}

	public java.util.Date getAccessionTime() {
		return this.accessionTime;
	}

	public void setAccessionTime(java.util.Date aValue) {
		this.accessionTime = aValue;
	}

	public Short getStatus() {
		return this.status;
	}

	public void setStatus(Short aValue) {
		this.status = aValue;
	}

	public String getEducation() {
		return this.education;
	}

	public void setEducation(String aValue) {
		this.education = aValue;
	}

	public Short getTitle() {
		return this.title;
	}

	public void setTitle(Short aValue) {
		this.title = aValue;
	}

	public String getFullname() {
		return this.fullname;
	}

	public void setFullname(String aValue) {
		this.fullname = aValue;
	}

	public Short getDelFlag() {
		return delFlag;
	}

	public void setDelFlag(Short delFlag) {
		this.delFlag = delFlag;
	}

	/**
	 * Return the name of the first key column
	 */
	public String getFirstKeyColumnName() {
		return "userId";
	}

	public Set<AppRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<AppRole> roles) {
		this.roles = roles;
	}

	// public GrantedAuthority[] getAuthorities() {
	// GrantedAuthority[] rights = roles.toArray(new GrantedAuthority[roles
	// .size() + 1]);
	// rights[rights.length - 1] = new GrantedAuthorityImpl("ROLE_PUBLIC");
	// return rights;
	// }

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> rights = new ArrayList<GrantedAuthority>();
		for (AppRole role : roles) {
			rights.add(role);
		}
		// 不进行URL过滤
		rights.add(new SimpleGrantedAuthority("ROLE_PUBLIC"));
		return rights;
	}

	public boolean isAccountNonExpired() {
		return true;
	}

	public boolean isAccountNonLocked() {
		return true;
	}

	public boolean isCredentialsNonExpired() {
		return true;
	}

	public boolean isEnabled() {
		if (status == 1) {
			return true;
		}
		return false;
	}

	// overwrite for

	/**
	 * Return the Id (pk) of the entity
	 */
	public String getId() {
		return userId.toString();
	}

	public String getBusinessEmail() {
		return email;
	}

	public String getFamilyName() {
		return fullname;
	}

	public String getGivenName() {
		return fullname;
	}

	public boolean isSupperManage() {
		Set<AppRole> roles = getRoles();
		boolean flag = false;
		for (Iterator<AppRole> it = roles.iterator(); it.hasNext();) {
			AppRole role = it.next();
			if (role.getRoleId().shortValue() == AppRole.SUPER_ROLEID
					.shortValue()) {
				flag = true;
			}
		}
		return flag;
	}

	public Set<UserOrg> getOrgs() {
		return orgs;
	}

	public void setOrgs(Set<UserOrg> orgs) {
		this.orgs = orgs;
	}

	/**
	 * 取得用户所在部门
	 */
	public String getDepNames() {
		// depNames = "";
		// Iterator<Organization> it = getOrgs().iterator();
		// while (it.hasNext()) {
		// Organization org = it.next();
		// depNames += org.getOrgName() + ",";
		// }
		// if (depNames.length() > 0) {
		// depNames = depNames.substring(0, depNames.length() - 1);
		// }
		// return depNames;

		return getDepartment().getDepName();
	}

	public void setDepNames(String depNames) {
		this.depNames = depNames;
	}

	/**
	 * 取得用户所担任的职位
	 * 
	 * @return
	 */
	public String getPosNames() {
		// posNames = "";
		// Iterator<Position> it = getPositions().iterator();
		// while (it.hasNext()) {
		// Position p = it.next();
		// posNames += p.getPosName() + ",";
		// }
		// if (posNames.length() > 0) {
		// posNames = posNames.substring(0, posNames.length() - 1);
		// }
		// return posNames;

		return null;
	}

	public void setPosNames(String posNames) {
		this.posNames = posNames;
	}

	/**
	 * 取得用户所拥有的角色
	 * 
	 * @return
	 */
	public String getRoleNames() {
		roleNames = "";
		Iterator<AppRole> it = getRoles().iterator();
		while (it.hasNext()) {
			AppRole ar = it.next();
			roleNames += ar.getRoleName() + ",";
		}
		if (roleNames.length() > 0) {
			roleNames = roleNames.substring(0, roleNames.length() - 1);
		}
		return roleNames;
	}

	/**
	 * 是否为超级管理员
	 * 
	 * @return
	 */
	public boolean isSuperAdmin() {
		Iterator<AppRole> it = getRoles().iterator();
		while (it.hasNext()) {
			AppRole ar = it.next();
			if ("超级管理员".equals(ar.getRoleName())) {
				return true;
			}
		}
		return false;
	}

	public void setRoleNames(String roleNames) {
		this.roleNames = roleNames;
	}

	public void init() {

		// 进行合并权限的处理
		Set<AppRole> roleSet = getRoles();
		// Set<Position> posSet = getPositions();
		// Iterator<Position> posit = posSet.iterator();
		// while (posit.hasNext()) {
		// Position pos = posit.next();
		// roleSet.addAll(pos.getRoles());
		// }
		Iterator<AppRole> it = roleSet.iterator();

		while (it.hasNext()) {
			AppRole role = it.next();
			if (role.getRoleId().equals(AppRole.SUPER_ROLEID)) {// 具有超级权限
				getRights().clear();
				getTopModules().clear();
				getRights().add(AppRole.SUPER_RIGHTS);
				getTopModules().putAll(AppUtil.getAllTopModels());
				break;
			} else {
				if (StringUtils.isNotEmpty(role.getRights())) {
					String[] items = role.getRights().split("[,]");
					for (int i = 0; i < items.length; i++) {
						String item = items[i];
						// 代表模板菜单,即上面的菜单
						if (item.startsWith("Mod_")) {
							if (!getTopModules().containsKey(item)) {
								getTopModules().put(items[i],
										AppUtil.getAllTopModels().get(item));
							}
							continue;
						}
						if (!getRights().contains(item)) {
							getRights().add(item);
						}
					}
				}
			}
		}

	}

	/**
	 * 初始化菜单权限信息
	 */
	public void initMenuRights() {
		// 取得公共TopMenuId
		getTopModules().putAll(AppUtil.getPublicTopModules());

		// 进行合并权限的处理
		Set<AppRole> roleSet = getRoles();
		Iterator<AppRole> it = roleSet.iterator();

		while (it.hasNext()) {
			AppRole role = it.next();
			if (role.getRoleId().equals(AppRole.SUPER_ROLEID)) {// 具有超级权限
				getRights().clear();
				getTopModules().clear();
				getRights().add(AppRole.SUPER_RIGHTS);
				getTopModules().putAll(AppUtil.getAllTopModels());
				break;
			} else {
				if (StringUtils.isNotEmpty(role.getRights())) {
					String[] items = role.getRights().split("[,]");
					for (int i = 0; i < items.length; i++) {
						String item = items[i];
						// 代表模板菜单,即上面的菜单
						if (item.startsWith("Mod_")) {
							if (!getTopModules().containsKey(item)) {
								getTopModules().put(items[i],
										AppUtil.getAllTopModels().get(item));
							}
							continue;
						}
						if (!getRights().contains(item)) {
							getRights().add(item);
						}
					}
				}
			}
		}

		// 排序用户的topModules;
		List<TopModule> list = new ArrayList<TopModule>();
		list.addAll(getTopModules().values());
		Collections.sort(list, new Comparator<TopModule>() {
			public int compare(TopModule o1, TopModule o2) {
				if (o1.getSn() > o2.getSn()) {
					return 1;
				}
				return 0;
			}
		});
		getTopModules().clear();
		for (TopModule topMod : list) {
			getTopModules().put(topMod.getId(), topMod);
		}
	}

	public Integer getOrgSn() {
		return orgSn;
	}

	public void setOrgSn(Integer orgSn) {
		this.orgSn = orgSn;
	}

	public Integer getUserSn() {
		return userSn;
	}

	public void setUserSn(Integer userSn) {
		this.userSn = userSn;
	}

	public String getDutyIds() {
		return dutyIds;
	}

	public void setDutyIds(String dutyIds) {
		this.dutyIds = dutyIds;
	}

	public String getDutyNames() {
		return dutyNames;
	}

	public void setDutyNames(String dutyNames) {
		this.dutyNames = dutyNames;
	}

	public Long getOrgId() {
		return orgId;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}

	public String getUserCode() {
		return userCode;
	}

	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}

	public void setRoleType(int roleType) {
		this.roleType = roleType;
	}

	public int getRoleType() {
		return roleType;
	}

	public Integer getXtcnt() {
		return xtcnt;
	}

	public void setXtcnt(Integer xtcnt) {
		this.xtcnt = xtcnt;
	}

	public String getZhicheng() {
		return zhicheng;
	}

	public void setZhicheng(String zhicheng) {
		this.zhicheng = zhicheng;
	}

	public String getJiaoyanshi() {
		return jiaoyanshi;
	}

	public void setJiaoyanshi(String jiaoyanshi) {
		this.jiaoyanshi = jiaoyanshi;
	}
		
}
